const yearZeroOffsets = [
  0, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50
];

let yearZeroOffsetIndex = 0;

function mapYearToLandscapeZ (year, offset, yearIntervals) {
  let z = 0;
  year = year || 0;

  if (year === 0 && offset) {
    year += yearZeroOffsets[yearZeroOffsetIndex];
    yearZeroOffsetIndex = (yearZeroOffsetIndex + 1) % yearZeroOffsets.length;
  }

  for (let i = 0; i < yearIntervals.length; i++) {
    const iv = yearIntervals[i];

    if (year > iv.start) {
      break;
    }

    const d = Math.min(iv.start - iv.end, iv.start - year);

    z += d * iv.yearLength;
  }

  return 1900*0.2 + 100*0.3 + 50*0.4 + 50*0.8 - z;
}


function initObjects () {
  var blobs = new THREE.Object3D();
  blobs.frustumCulled = false;

  var sticks = new THREE.Object3D();
  sticks.frustumCulled = false;

  return {
    blobs: blobs,
    sticks: sticks
  };
}

function bindEvent (obj, cb) {
  obj.addEventListener('resize', cb, false);
}


function blobTextures () {
  var loadingPercentageMax = 0;
  var blobTextures = [];

  for (var i = 0; i < 16; i++) {
    var path = 'http://localhost:5000/img/blob_'+ i +'.png';
    var tex = new THREE.ImageUtils.loadTexture(path, undefined, function() {
      loadingPercentageMax += 2;
    }, function() {
      loadingPercentageMax += 2;
    });

    tex.premultiplyAlpha = true;
    blobTextures.push(tex);
  }

  return blobTextures;
}

function framer () {
  return (
    (window.performance && window.performance.now && window.performance.now.bind(window.performance)) ||
    Date.now.bind(Date)
  );
}
